package com.walkline.screen;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.music.MusicSDK;
import com.walkline.music.inf.Album;
import com.walkline.music.inf.Albums;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;

public final class NewAlbumScreen extends MainScreen
{
	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _albumsSet = new ListStyleButtonSet();
	ListStyleButtonField _item;
	MusicSDK _music;

    public NewAlbumScreen(MusicSDK music)
    {
    	super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

        setTitle("最新专辑");

        _music = music;
        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run()
			{
				getAlbumsList();
			}
		});
    }

	private void getAlbumsList()
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_music, null, RefreshActions.ALBUMSLIST);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Albums albumsList = popupScreen.getAlbumsList();

		if (popupScreen != null) {popupScreen = null;}
		if (albumsList != null) {refreshAlbumsList(albumsList);}
	}

	private void refreshAlbumsList(Albums list)
	{
		Album[] albumList = list.getAlbums();
		Album album;

		if (albumList.length <= 0) {return;}

		if (_albumsSet.getManager() == null) {_foreground.add(_albumsSet);}
		if (_albumsSet.getFieldCount() > 0) {_albumsSet.deleteAll();}

		for (int i=0; i<albumList.length; i++)
		{
			album = albumList[i];
			if (album != null)
			{
				_item = new ListStyleButtonField(album);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC)
						{
							ListStyleButtonField item = (ListStyleButtonField) _albumsSet.getFieldWithFocus();
							UiApplication.getUiApplication().pushScreen(new AlbumListScreen(_music, item.getAlbum()));
						}
					}
				});
				_albumsSet.add(_item);
			}
		}
	}

	protected boolean onSavePrompt() {return true;}
}